const router = require('koa-router')()

const { login, register, isExitUser } = require('../controller/user')
const { SuccessModel, ErrorModel } = require('../module/resModel')
const { genPassword } = require('../utils/cryp')

router.prefix('/api/user')

// 登录
router.post('/login', async function (ctx, next) {
  const { username, password } = ctx.request.body
  const res = await login(username, genPassword(password))
  if (!res) {
    ctx.body = new ErrorModel('username or password is wrong!')
    return
  }
  ctx.session.username = username
  ctx.session.password = password
  ctx.body = new SuccessModel(res, 'login success')
})
// 注册
router.post('/register', async function (ctx, next) {
  const { username, password, realname } = ctx.request.body
  const isExitRes = await isExitUser(username)
  if (isExitRes) {
    ctx.body = new ErrorModel('用户已经存在!')
    return
  } else {
    const res = await register(
      username,
      genPassword(password),
      realname,
      username
    )
    ctx.body = new SuccessModel(res, 'register success')
  }
})

module.exports = router
